<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;

class Product extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = 'default';

    protected $table = 'product';

    public function _initialize(){
        parent::_initialize();

        $category = Db::name('category')->where([
            'pid' => 0
        ])->order('weigh desc,id desc')->select();
        foreach ($category as $k => &$v){
            $v['son'] = Db::name('category')->where([
                'pid' => $v['id']
            ])->order('weigh desc,id desc')->select();
        }
        $this->assign('category',$category);

    }

    public function index()
    {
        $cate_id = input('cate_id/d','');
        if(!$cate_id){
            $cate_id = Db::name('category')->order('weigh desc,id desc')->value('id');
        }
        $this->assign('cate_id',$cate_id);

        $keyword = input('keyword/s','');

        $where = [];
        if($cate_id){
            $where['cate_id'] = $cate_id;
            $cate_name = Db::name('category')->where([
                'id' => $cate_id
            ])->value('name');
            $this->assign('cate_name',$cate_name);
        }else{
            $this->assign('cate_name','');
        }


        if($keyword){
            $where['title'] = ['like','%'.$keyword.'%'];
        }

        $data = Db::name($this->table)->where($where)->order('weigh desc,id desc')->paginate(12);
        $page = $data->render();
        $this->assign('page',$page);
        $this->assign('lists', $data);
        return $this->view->fetch();
    }

    public function detail()
    {
        $id = input('id/d','');

        $data = Db::name($this->table)->where('id',$id)->find();
        Db::name($this->table)->where('id',$id)->setInc('hits');
        $this->assign('detail',$data);

        if($data['cate_id']){
            $cate_name = Db::name('category')->where([
                'id' => $data['cate_id']
            ])->value('name');
            $this->assign('cate_name',$cate_name);
        }else{
            $this->assign('cate_name','');
        }

        $next = Db::name($this->table)->where('id','>',$id)->order('id asc')->find();
        $this->assign('next',$next);
        $prev = Db::name($this->table)->where('id','<',$id)->order('id desc')->find();
        $this->assign('prev',$prev);

        return $this->view->fetch();
    }

}
